
/**
 * 分片
 * @param {array} arr
 * @param {number} size - 分片大小， >= 1
 * @param {function} [fn] - 分片回调函数
 * @returns {array} - 返回分片数组
 * **/
export function fragment (arr, size, fn) {
  if (!size || size < 0) throw new Error('`size` must be greater than or equal to 1')

  const length = arr.length
  const times = Math.ceil(length / size)
  const newArr = []
  const isFun = typeof fn === 'function'

  for (let i = 0; i < times; i++) {
    const start = i * size
    let end = start + size
    end = end > length ? length : end

    const chunk = arr.slice(start, end)

    newArr.push(isFun ? fn(chunk, i, start, end, arr) : chunk)
  }

  return newArr
}

/**
 * 挑拣对象属性
 * @param {object} obj
 * @param {Array} keys - 需要挑拣的key
 * @param {(v, k) => boolean} [fn] - 自定义挑拣函数
 * **/
export function pickBy (obj, keys, fn = v => v !== undefined) {
  const data = {}
  for (const i in keys) {
    const key = keys[i]
    if (fn(obj[key], key)) {
      data[key] = obj[key]
    }
  }
  return data
}

/**
 * 字符串绑变量
 * @param {string} str - 字符串
 * @param {object} params - 参数
 * @returns {string}
 * **/
export function bindString (str, params) {
  if (!str) return str
  return str.replace(/:(\w+)/g, (txt, key) => {
    return Object.prototype.hasOwnProperty.call(params, key) ? params[key] : txt
  })
}

/**
 * 格式化文件大小
 * @param {number} size - 文件大小，单位byte
 * @returns {string}
 * **/
export function formatFileSize (size) {
  var arr = [Math.pow(1024, 4), Math.pow(1024, 3), Math.pow(1024, 2), 1024]
  var unit = ['TB', 'GB', 'MB', 'KB', 'B']

  if (+size < 1024) return (+size).toFixed(2) + unit[4]

  for (var i in arr) {
    var val = size / arr[i]
    if (val >= 1) {
      return val.toFixed(2) + unit[i]
    }
  }
}

/**
 * 秒转播放器时长格式
 * @param {number} time - 时长，单位s
 * @returns {string}
 * **/
export function formatDuration (time) {
  if (!+time) return '00:00'

  var hour = time >= 3600 ? parseInt(time % (3600 * 60) / 3600) : 0
  var minutes = time >= 60 ? parseInt(time % 3600 / 60) : 0
  var seconds = parseInt(time % 60)
  var arr = []

  if (hour > 0) {
    arr.push(hour < 10 ? '0' + hour : hour)
  }

  minutes = minutes < 10 ? '0' + minutes : minutes
  seconds = seconds < 10 ? '0' + seconds : seconds

  arr.push(minutes)
  arr.push(seconds)
  return arr.join(':')
}
